package cn.wolfcode.shop.cloud.service.impl;

import cn.wolfcode.shop.cloud.common.BusinessException;
import cn.wolfcode.shop.cloud.domain.User;
import cn.wolfcode.shop.cloud.mapper.UserMapper;
import cn.wolfcode.shop.cloud.redis.MemberKeyPrefix;
import cn.wolfcode.shop.cloud.redis.RedisService;
import cn.wolfcode.shop.cloud.service.IUserService;
import cn.wolfcode.shop.cloud.util.MD5Util;
import cn.wolfcode.shop.cloud.util.MemberCodeMsg;
import cn.wolfcode.shop.cloud.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;

@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisService redisService;

    @Override
    public User get(Long id) {
        return userMapper.findById(id);
    }

    @Override
    public String doLogin(LoginVo vo) {
        /*//判断账号密码不能为空
        if (StringUtils.isEmpty(vo.getUsername())||StringUtils.isEmpty(vo.getPasswored())){
            throw new BusinessException(MemberCodeMsg.LOGIN_ERROR);
        }*/
        //根据账号去查询数据库是否有数据
        long id = Long.parseLong(vo.getUsername());
        User user = this.get(id);
        if (user == null){
            throw new BusinessException(MemberCodeMsg.LOGIN_OPTION);
        }
        //对比密码
        String pass = MD5Util.encodeCry(user.getSalt(),vo.getPasswored());
        if(!pass.equals(user.getPassword())){
            throw new BusinessException(MemberCodeMsg.LOGIN_OPTION);
        }
        String token = createToken(user);
        return token;
    }

    @Override
    public boolean refreshToken(String token) {
        if (redisService.exists(MemberKeyPrefix.USER_TOKEN, token)){
            redisService.expire(MemberKeyPrefix.USER_TOKEN,token);
            return true;
        }else {
            return false;
        }
    }

    @Override
    public User getCurrentUser(String token) {
        if (!StringUtils.isEmpty(token)){
            return redisService.get(MemberKeyPrefix.USER_TOKEN,token,User.class);
        }
        return null;
    }

    private String createToken(User user) {
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        //存入redis
        redisService.set(MemberKeyPrefix.USER_TOKEN,token,user);
        return token;
    }
}